<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章编辑</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <!-- 引入UEditor样式文件 -->
    <link rel="stylesheet" href="/libs/ueditor/themes/default/css/ueditor.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .form-item {
            margin-bottom: 15px;
        }
        
        .form-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-item input, .form-item select, .form-item textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .form-item textarea {
            min-height: 200px;
            resize: vertical;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .btn-success {
            background-color: #67c23a;
            color: white;
        }
        
        .btn-warning {
            background-color: #e6a23c;
            color: white;
        }
        
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th, .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .table th {
            background-color: #f5f7fa;
            font-weight: bold;
        }
        
        .status-draft {
            color: #909399;
        }
        
        .status-published {
            color: #67c23a;
        }
        
        .status-unpublished {
            color: #f56c6c;
        }
        
        .actions {
            white-space: nowrap;
        }
        
        .action-btn {
            background: none;
            border: none;
            color: #409eff;
            cursor: pointer;
            margin-right: 5px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .search-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .search-form input, .search-form select {
            flex: 1;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
        }
        
        .search-form .btn {
            margin-right: 0;
        }
        
        /* UEditor 容器样式 */
        #editorContainer {
            width: 100%;
        }
        
        #editorContainer .edui-editor {
            width: 100% !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2 id="pageTitle">文章编辑</h2>
        </div>
        
        <div class="card">
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            
            <form id="articleForm">
                <input type="hidden" id="articleId">
                <div class="form-item">
                    <label for="articleTitle">文章标题</label>
                    <input type="text" id="articleTitle" required>
                </div>
                <div class="form-item">
                    <label for="articleCategory">分类</label>
                    <select id="articleCategory" required>
                        <option value="">请选择分类</option>
                    </select>
                </div>
                <div class="form-item">
                    <label for="articleContent">内容</label>
                    <!-- UEditor容器 -->
                    <div id="editorContainer"></div>
                </div>
                <div class="form-item">
                    <label for="articleStatus">状态</label>
                    <select id="articleStatus">
                        <option value="0">草稿</option>
                        <option value="1">已发布</option>
                        <option value="2">已下架</option>
                    </select>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn btn-default" onclick="cancelEdit()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    <script src="/js/http-client.js"></script>
    <!-- 引入UEditor核心文件 -->
    <script src="/libs/ueditor/ueditor.config.js"></script>
    <script src="/libs/ueditor/ueditor.all.js"></script>
    
    <script>
        // 当前文章数据
        let articles = [];
        let categories = [];
        let editingArticle = null;
        let ue = null; // UEditor实例
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', async function() {
            showLoading(true);
            
            // 初始化UEditor
            initUEditor();
            
            await Promise.all([
                loadAuthorizedCategories(),
                loadArticle()
            ]);
            updateCategoryOptions();
            showLoading(false);
        });
        
        // 初始化UEditor
        function initUEditor() {
            // 配置UEditor
            window.UEDITOR_CONFIG = {
                UEDITOR_HOME_URL: "/libs/ueditor/",
                serverUrl: "",
                toolbars: [[
                    'fullscreen', 'source', '|',
                    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
                    'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                    'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                    'touppercase', 'tolowercase', '|',
                    'link', 'unlink', 'anchor', '|',
                    'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
                    'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
                    'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
                    'print', 'preview', 'searchreplace', 'help', 'drafts'
                ]],
                initialFrameHeight: 400,
                zIndex: 9999
            };
            
            // 创建UEditor实例
            ue = UE.getEditor('editorContainer');
            
            // 监听编辑器内容变化
            ue.ready(function() {
                console.log('UEditor 初始化完成');
            });
        }
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const articleForm = document.getElementById('articleForm');
            
            if (show) {
                if (loadingIndicator) loadingIndicator.style.display = 'block';
                if (articleForm) articleForm.style.display = 'none';
            } else {
                if (loadingIndicator) loadingIndicator.style.display = 'none';
                if (articleForm) articleForm.style.display = 'block';
            }
        }
        
        // 加载文章数据
        async function loadArticle() {
            const urlParams = new URLSearchParams(window.location.search);
            const articleId = urlParams.get('id');
            
            if (articleId) {
                // 检查ID是否为有效数字
                if (!/^\d+$/.test(articleId)) {
                    alert('无效的文章ID');
                    return;
                }
                
                try {
                    const article = await httpClient.get(`/article/${articleId}`);
                    editingArticle = article;
                    document.getElementById('pageTitle').textContent = '编辑文章';
                    document.getElementById('articleId').value = article.id;
                    document.getElementById('articleTitle').value = article.title;
                    document.getElementById('articleStatus').value = article.status;
                    
                    // 等待UEditor准备就绪后设置内容
                    ue.ready(function() {
                        ue.setContent(article.content || '');
                    });
                } catch (error) {
                    console.error('获取文章数据异常:', error);
                }
            } else {
                document.getElementById('pageTitle').textContent = '新增文章';
            }
        }
        
        // 加载授权的分类数据
        async function loadAuthorizedCategories() {
            try {
                categories = await httpClient.get('/category/authorized');
                console.log('获取到授权分类:', categories);
            } catch (error) {
                console.error('获取分类数据异常:', error);
                // 如果获取授权分类异常，回退到获取所有分类
                await loadCategories();
            }
        }
        
        // 加载所有分类数据（备用方法）
        async function loadCategories() {
            try {
                categories = await httpClient.get('/category/tree');
                console.log('获取到所有分类:', categories);
            } catch (error) {
                console.error('获取分类数据异常:', error);
            }
        }
        
        // 获取cookie中的token
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }
        
        // 更新分类选项
        function updateCategoryOptions() {
            const categorySelect = document.getElementById('articleCategory');
            
            console.log('更新分类选项，当前分类:', categories);
            
            function addOptions(cats, prefix = '') {
                cats.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = prefix + cat.name;
                    categorySelect.appendChild(option);
                    
                    if (cat.children && cat.children.length > 0) {
                        addOptions(cat.children, prefix + '　');
                    }
                });
            }
            
            // 保留第一个选项（请选择分类）
            const firstOption = categorySelect.firstElementChild;
            categorySelect.innerHTML = '';
            categorySelect.appendChild(firstOption);
            
            // 只有当有分类数据时才添加选项
            if (categories && categories.length > 0) {
                addOptions(categories);
            } else {
                console.log('没有分类数据可显示');
            }
            
            // 如果正在编辑文章，设置选中的分类
            if (editingArticle) {
                console.log('设置选中分类:', editingArticle.categoryId);
                categorySelect.value = editingArticle.categoryId;
            }
        }
        
        // 取消编辑
        function cancelEdit() {
            if (confirm('确定要取消编辑吗？未保存的更改将会丢失。')) {
                window.close();
            }
        }
        
        // 表单提交处理
        document.getElementById('articleForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const id = document.getElementById('articleId').value;
            const title = document.getElementById('articleTitle').value;
            const categoryId = document.getElementById('articleCategory').value;
            const content = ue.getContent(); // 从UEditor获取内容
            const status = document.getElementById('articleStatus').value;
            
            if (!title || !categoryId || !content) {
                alert('请填写完整信息');
                return;
            }
            
            // 验证分类ID是否为数字
            if (!/^\d+$/.test(categoryId)) {
                alert('请选择有效的分类');
                return;
            }
            
            const articleData = {
                title,
                categoryId: parseInt(categoryId),
                content,
                status: parseInt(status),
                authorId: 1 // 示例作者ID，实际应该从用户信息中获取
            };
            
            // 如果是发布状态，设置发布时间
            if (status == 1 && !editingArticle?.publishTime) {
                articleData.publishTime = new Date();
            }
            
            try {
                if (id) {
                    // 验证文章ID是否为数字
                    if (!/^\d+$/.test(id)) {
                        alert('无效的文章ID');
                        return;
                    }
                    
                    // 更新文章
                    await httpClient.put(`/article/${id}`, articleData);
                    alert('更新成功');
                } else {
                    // 创建文章
                    await httpClient.post('/article', articleData);
                    alert('创建成功');
                }
                
                window.close();
                // 如果窗口没有关闭，返回列表页面
                window.location.href = '/article';
            } catch (error) {
                console.error('保存文章异常:', error);
                alert('保存文章时发生错误');
            }
        });
    </script>
</body>
</html>